package com.xlh.service.impl;

import cn.hutool.core.codec.Base64;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.RandomUtil;
import com.xlh.enums.LocalResourcesEnum;
import com.xlh.exception.common.GlobalException;
import com.xlh.service.ResourceService;
import org.apache.commons.io.FileUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;

/**
 * @author zhr 2019/3/14
 */
@Service
public class ResourceServiceImpl implements ResourceService {

    @Override
    public String uploadMarkdownPicture(MultipartFile file) {
        if (file == null) return null;

        String fileName = file.getOriginalFilename();

        fileName = StringUtils.join(RandomUtil.simpleUUID(), fileName.substring(fileName.lastIndexOf(".")));

        // 创建文件目录
        String dir = LocalResourcesEnum.MARKDOWN_PICTURE.getLocalUploadPath();
        if (!new File(dir).exists()) {
            FileUtil.mkdir(dir);
        }

        String filePath = LocalResourcesEnum.MARKDOWN_PICTURE.getLocalUploadPath(fileName);

        // 写入文件
        File newFile = new File(filePath);
        try {
            FileUtils.copyInputStreamToFile(file.getInputStream(), newFile);
        } catch (IOException e) {
            throw new GlobalException("图片上传失败");
        }

        return LocalResourcesEnum.MARKDOWN_PICTURE.getMappingUrl(fileName);
    }

    @Override
    public String savePictureAsFile(String base64Info) {
        if (StringUtils.isBlank(base64Info)) {
            return null;
        }
        String fileName = StringUtils.join(RandomUtil.simpleUUID(), ".png");

        // 创建文件目录
        String dir = LocalResourcesEnum.MARKDOWN_PICTURE.getLocalUploadPath();
        if (!new File(dir).exists()) {
            FileUtil.mkdir(dir);
        }

        String filePath = LocalResourcesEnum.MARKDOWN_PICTURE.getLocalUploadPath(fileName);

        File file = new File(filePath);

        byte[] buffer = Base64.decode(base64Info.split("base64,")[1]);
        FileUtil.writeBytes(buffer, file);

        return LocalResourcesEnum.MARKDOWN_PICTURE.getMappingUrl(fileName);
    }
}
